import aiohttp
from io import BytesIO
from PIL import Image
import logging

keyword = "/st"
help_content = "\n该文件仅用作一种模块和回复方式示例，原用于主APbot复杂功能，现在新的都写plugins里"
help_short = "色图 /st"


async def register(cmd_handler, lock, reply) -> bool:
    try:
        cmd_handler.add_handler(keyword, Handler(lock, reply).main, help_short)
        logging.info(f"✅ - {keyword}")
        return True
    except Exception as e:
        logging.exception(f"❌ - {keyword} : {e}")
        return False


class Handler:

    def __init__(self, lock, reply) -> None:
        self.lock = lock
        self.reply = reply
        self.keyword = keyword
        self.infos = {}
        # 特有 
        self.lolicon_api = "https://api.lolicon.app/setu/v2?size=regular"

    async def init_state(self, message) -> None:
        self.message = message
        self.msg = self.message.content.strip()
        self.args = self.msg[len(keyword):].strip().split()
        self.userID = self.infos["userID"]
        self.groupID = self.infos["groupID"]
        self.admin = self.infos["admin"]

    async def main(self, message, infos):
        self.infos = infos
        await self.init_state(message)

        cmd = self.args[0].lower() if self.args else None

        if cmd in ["帮助", "help"]:
            return await self.reply(content=help_content)
        # if self.admin == True:
        else:
            return await self.setu()

    async def setu(self) -> None:
        async with self.lock:
            img = await self.lolicon_setu(self.args)
            # 也可以直接reply(img_url=img)或者url读取成base64然后reply(img_b64=img)
            # 腾讯有时候下载图片还没bot服务器快的时候就下载下来再传了
            if img == None:
                return await self.reply(
                    content="没搜到", image="./assets/img/azusa.gif"
                )
            else:
                return await self.reply(
                    image="./data/cache/send/setu.jpg", delete_after_send=True
                )

    async def lolicon_setu(self, tag_list=None) -> None:
        """
        根据tag进行请求获取图片，返回图片BytesIO, 图片链接, 原始请求结果
        """
        lolicon_api = self.lolicon_api
        api = lolicon_api

        if tag_list is not None:
            api = lolicon_api + "&" + "&".join(f"tag={tag_list}")
        async with aiohttp.ClientSession() as session:
            async with session.get(api) as resp:
                result = await resp.json()

            if not result["data"]:
                return None
            img_url = result["data"][0]["urls"]["regular"]  # 可以直接发url，不过tx下这个api.lolicon.app挺慢的，就保存到本地再发了
            async with session.get(img_url) as resp:
                img = BytesIO(await resp.read())
                pil_img = Image.open(img)
                pil_img.save("./data/cache/send/setu.jpg")
                return img_url
